package com.hqyj.springtest.util;

import java.util.Date;
import java.util.HashMap;

import org.springframework.stereotype.Component;

import com.hqyj.springtest.pojo.SysUser;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public class JWTUtil {
	// ����һ��token�Ĺ���ʱ��
	private long exp = 30*60*1000 ;
	// ���ü��ܵ���Կ
	private String  secret ="i.love.you";
	
	// -- ����token
	public String createToken(SysUser sysUser) {
		JwtBuilder builder = Jwts.builder();
		builder.claim("user", sysUser); // ����һ��user��
		/*
		HashMap<String, Object> map = new HashMap<String, Object>() ; 
		map.put("user", sysUser);
		builder.setClaims(map);
		*/
		builder.setSubject(sysUser.getUname());
		builder.setIssuedAt(new Date()) ;// ���÷������ڣ�token��Ч��ʱ�䣩
		builder.setExpiration(new Date(exp + System.currentTimeMillis())); // ���ù���ʱ��
		// signature algorithm
	    builder.signWith(SignatureAlgorithm.HS512, secret);
		String token  = builder.compact();
		return token;
	}
	
	// -- ����token
	// -- Claims ��Map������
	public Claims parseToken(String token) {
		JwtParser parser = Jwts.parser();
		parser.setSigningKey(secret); //������Կ 
		Jws<Claims> parseClaimsJws = parser.parseClaimsJws(token); // ����token
		Claims body = parseClaimsJws.getBody();
		return body;
	}
	
	// -- �ж�token�Ƿ���Ч�ķ���
	public boolean validToken(String token) {
		 try {
			 parseToken(token);
		     return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	
	public static void main(String[] args) {
		JWTUtil js = new JWTUtil();
		SysUser syu = new SysUser();
		syu.setUid(100); syu.setUname("alice") ; syu.setUpwd("1234");
		//String token = js.createToken(syu);
		// eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyIjp7InVpZCI6MTAwLCJ1bmFtZSI6ImFsaWNlIiwidXB3ZCI6IjEyMzQiLCJyaWQiOm51bGwsInVzdGFyIjpudWxsfSwic3ViIjoiYWxpY2UiLCJpYXQiOjE2MTAzMzIyNTksImV4cCI6MTYxMDMzNDA1OX0.gruBiPPGjaqenVZfUkQMAXGo6degj4H8az9brZPvlYKKECjNk_hty_O1wKXObxVI5zHhz8ADaK2sq8iiE8taFw
		//System.out.println(token);
		String token =  "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyIjp7InVpZCI6MTAwLCJ1bmFtZSI6ImFsaWNlIiwidXB3ZCI6IjEyMzQiLCJyaWQiOm51bGwsInVzdGFyIjpudWxsfSwic3ViIjoiYWxpY2UiLCJpYXQiOjE2MTAzMzIyNTksImV4cCI6MTYxMDMzNDA1OX0.gruBiPPGjaqenVZfUkQMAXGo6degj4H8az9brZPvlYKKECjNk_hty_O1wKXObxVI5zHhz8ADaK2sq8iiE8taFw";
		Claims claims = js.parseToken(token);
		System.out.println(claims.get("user"));
		System.out.println(js.validToken(token));
		
	}
}
